package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.network.entity.Entity;
import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.service.DeleteShoppingCartService;
import com.zw.yzk.kabu.data.network.task.DeleteShoppingCartTask;

import java.net.URLEncoder;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2016/12/24.
 */

public class DeleteShoppingCartRepository extends CommonRepository {

    @Inject
    public DeleteShoppingCartRepository() {
    }

    @Override
    protected Observable connectServer(Task task) {
        DeleteShoppingCartService service = ServiceGenerator.createService(DeleteShoppingCartService.class);
        DeleteShoppingCartTask deleteShoppingCartTask = (DeleteShoppingCartTask) task;
        deleteShoppingCartTask.accessToken = URLEncoder.encode(deleteShoppingCartTask.accessToken);

        StringBuilder idList = new StringBuilder("[");
        for (Integer integer : deleteShoppingCartTask.shoppingCartList) {
            idList.append(String.valueOf(integer)).append(",");
        }
        String id = idList.deleteCharAt(idList.length() - 1).append("]").toString();
        String deleteUrl = Constant.BASE_URL +
                "api/shoppingcart" +
                "?user_id=" +
                deleteShoppingCartTask.userId +
                "&access_token=" +
                deleteShoppingCartTask.accessToken +
                "&shoppingcart_id_list=" +
                id;
        return service.deleteShoppingCart(deleteUrl);
    }

    @Override
    protected Func1<Entity, Observable> getServerData() {
        return new Func1<Entity, Observable>() {
            @Override
            public Observable call(Entity entity) {
                return Observable.just(entity.errCode == Constant.RESULT_OK);
            }
        };
    }

}
